package cn.qiba.sms.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.qiba.sms.controller.common.AuthenticatedController;
import cn.qiba.sms.db.dao.SmsInfoRepository;
import cn.qiba.sms.db.entity.SmsInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
public class IndexController extends AuthenticatedController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SmsInfoRepository smsInfoRepository;

    @Value("${spring.security.user.name}")
    private String name;
    @Value("${spring.security.user.password}")
    private String pwd;

    @Value("${platform.name}")
    private String platformName;


    @GetMapping("/admin")
    String index(ModelMap modelMap,HttpServletRequest request){
        Map param = getParameterMap(request);

        String phone = request.getParameter("phone");
        String status = request.getParameter("status");
        String beginTime = request.getParameter("beginTime");
        String endTime = request.getParameter("endTime");


        String pageNumber = request.getParameter("pn");
        if(StrUtil.isEmpty(pageNumber)){
            pageNumber = "0";
        }
        int pageSize = 10;

        Date now = new Date();
        long totalToday = smsInfoRepository.countByCreateTimeBetween(DateUtil.beginOfDay(now),DateUtil.endOfDay(now));//今日数量
        modelMap.put("totalToday",totalToday);
        long totalSending = smsInfoRepository.countByStatus("0");//发送中数量
        modelMap.put("totalSending",totalSending);
        long totalSuccess = smsInfoRepository.countByStatus("1");//成功数量
        modelMap.put("totalSuccess",totalSuccess);
        long totalError = smsInfoRepository.countByStatus("2");//失败数量
        modelMap.put("totalError",totalError);
        modelMap.put("total",totalSending+totalSuccess+totalError);


        Specification<SmsInfo> specification = new Specification<SmsInfo>() {
            @Override
            public Predicate toPredicate(Root<SmsInfo> root,
                                         CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Predicate p = null;
                if(StrUtil.isNotEmpty(status)){
                    Predicate pd = criteriaBuilder.equal(root.get("status"), status);
                    p = criteriaBuilder.and(pd);
                }
                if(StrUtil.isNotEmpty(phone)){
                    Predicate pd = criteriaBuilder.equal(root.get("phone"), phone);
                    p = criteriaBuilder.and(pd);
                }
                if(StrUtil.isNotEmpty(beginTime) && StrUtil.isNotEmpty(endTime)){
                    Predicate pd = criteriaBuilder.between(root.get("createTime"), DateUtil.parse(beginTime),DateUtil.parse(endTime+" 23:59:59","yyyy-MM-dd HH:mm:ss"));
                    p = criteriaBuilder.and(pd);
                }else if(StrUtil.isNotEmpty(beginTime)){
                    Predicate pd = criteriaBuilder.greaterThanOrEqualTo(root.get("createTime"), DateUtil.parse(beginTime));
                    p = criteriaBuilder.and(pd);
                }else if(StrUtil.isNotEmpty(endTime)){
                    Predicate pd = criteriaBuilder.lessThanOrEqualTo(root.get("createTime"), DateUtil.parse(endTime+" 23:59:59","yyyy-MM-dd HH:mm:ss"));
                    p = criteriaBuilder.and(pd);
                }
                return p;
            }
        };
        Sort sort = new Sort(Sort.Direction.DESC,"createTime"); //创建时间降序排序
        Pageable pageable = new PageRequest(Integer.parseInt(pageNumber),pageSize,sort);

        Page<SmsInfo> page = smsInfoRepository.findAll(specification,pageable);
        logger.info(JSONUtil.toJsonStr(page));
        modelMap.put("page",page);
        modelMap.put("pn",Integer.parseInt(pageNumber)+1);
        modelMap.put("totalPage",page.getTotalPages());
        modelMap.put("totalCount",page.getTotalElements());
        modelMap.put("param",param);

        modelMap.put("platformName",platformName);

        return "index.html";
    }

    @GetMapping("/login")
    String login(HttpServletRequest request,ModelMap modelMap){
        logger.info("Controller ip :"+request.getAttribute("ip"));
        modelMap.put("platformName",platformName);
        return "login.html";
    }
    @GetMapping("/logout")
    String logout(HttpServletRequest request,ModelMap modelMap){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }

    @PostMapping("/login")
    String dologin(HttpServletRequest request, ModelMap modelMap){

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try{
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
        }catch (Exception e){
            modelMap.put("error",e.getMessage());
            return login(request,modelMap);
        }
        return "redirect:/admin";
    }

    @GetMapping("/404")
    String page404(HttpServletRequest request,ModelMap modelMap){
        modelMap.put("platformName",platformName);
        return "404.html";
    }
}

